//
//  ATStepNumberManager.m
//  ATGaode_demo
//
//  Created by Chengquan Ye on 2019/3/8.
//  Copyright © 2019年 Chengquan Ye. All rights reserved.
//

#import "ATStepNumberManager.h"
#import <CoreMotion/CoreMotion.h>

@interface ATStepNumberManager ()

/** 计算步数的对象 */
@property (strong, nonatomic) CMPedometer *pedonmeter;

@end

@implementation ATStepNumberManager

+ (instancetype)manager
{
    return [[ATStepNumberManager alloc] init];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.pedonmeter = [[CMPedometer alloc] init];
    }
    return self;
}

- (void)stopCountingStepNumber
{
    [self.pedonmeter stopPedometerUpdates];
}

- (void)startCountingStepNumber:(NSDate *)startDate
{
    if ([CMPedometer isStepCountingAvailable]) {
        [self.pedonmeter startPedometerUpdatesFromDate:startDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
            NSLog(@"%@, error = %@", pedometerData.numberOfSteps, error);
            if (error)
            {
                NSLog(@"开始计步 error===%@",error);
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                    [dict setObject:pedometerData.numberOfSteps forKey:@"numberOfSteps"];
                    [dict setObject:pedometerData.distance forKey:@"distance"];
                    
                    if (self.delegate && [self.delegate respondsToSelector:@selector(stepNumber:)]) {
                        [self.delegate stepNumber:dict];
                    }
                });
            }
        }];
    } else {
        NSLog(@"计步器不可用");
    }
}

- (void)stepNumberWithStartDate:(NSDate *)startDate endDate:(NSDate *)endDate;
{
    if ([CMPedometer isStepCountingAvailable]) {
        [self.pedonmeter queryPedometerDataFromDate:startDate toDate:endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
            if (error)
            {
                NSLog(@"error===%@",error);
            }
            else {
                NSLog(@"步数===%@",pedometerData.numberOfSteps);
                NSLog(@"距离===%@",pedometerData.distance);
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                    [dict setObject:pedometerData.numberOfSteps forKey:@"numberOfSteps"];
                    [dict setObject:pedometerData.distance forKey:@"distance"];
                    
                    if (self.delegate && [self.delegate respondsToSelector:@selector(stepNumber:)]) {
                        [self.delegate stepNumber:dict];
                    }
                });
            }
        }];
    } else {
        NSLog(@"计步器不可用");
    }
}

@end
